<?php
namespace Home\Logic;

use Utuo\DistributionShopDonate;
use Utuo\DistributionShopScore;

class DistributionShopLogic {
    
    /**
     * 用户佣金
     * @param unknown $order
     */
    public function getOrderBonus( $order ) {
        /** 用户拥金结算 */
        /* 基础佣金 */
        $uids = explode(',', $order['reward_uids']);
        $bonus = explode(',', $order['reward_bonus']);
        $bonusUser = array_combine($uids, $bonus);
        
        /* 特销商佣金 */
        $uids = explode(',', $order['reward_uids_dealer']);
        $bonus = explode(',', $order['reward_bonus_dealer']);
        $bonusDealerUser = array_combine($uids, $bonus);
        
        /* 佣金合并 */
        $bindBonus = array();
        foreach ( $bonusUser as $k => $v) {
            if ( empty($k) ) continue;
            //if ( empty($v) ) continue; // 排除0分成订单
            $bindBonus[$k] += $v*1;
        }
        foreach ( $bonusDealerUser as $k => $v) {
            if ( empty($k) ) continue;
            //if ( empty($v) ) continue; // 排除0分成订单
            $bindBonus[$k] += $v*1;
        }
        return $bindBonus;
    }
    
    /**
     * 返币
     * @param unknown $order
     */
    public function saveCurrency( $order, $currencyConfig = array() ) {
        /* 用户订单佣金 */
        $bindBonus = $this->getOrderBonus($order);
        $event = M("DistributionShopScoreEvent")->where(array('cid'=>$this->cid, 'tag' => 'DistributionReward'))->find();
        if ( $event and $event['status'] ) { // 行为已启用
            $driverConfig = array(); // 行为驱动配置参数
            $event['cfg'] and $event['cfg'] = unserialize($event['cfg']);
            $event['cfg'] and $driverConfig = $event['cfg'];
            $scoreHandle = DistributionShopScore::getInstance("DistributionReward", array('cid' => $order['cid']), $driverConfig);
            foreach ($bindBonus as $k => $v ) {
                $currency = ceil($v*100/$currencyConfig['value']) and $scoreHandle->exec(array(
                    'uid' => $k,
                    'score' => $currency,
                ));
            }
        }
    } 

	/**
	 * 返佣
	 * @param unknown $order
	 */
	public function saveBonus( $order ) {
        /* 用户订单佣金 */
	    $bindBonus = $this->getOrderBonus($order);
	    
		/* 更新用户佣金收入与推广订单数量  */
		if ( $bindBonus ) {
			$setBonusFields = array();
			foreach ( $bindBonus as $k => $v ) {
				$setBonusFields[] = "WHEN {$k} THEN bonus+{$v}";
			}
			$setBonusFields = join(' ', $setBonusFields);
			$result = M("WechatUser")->where(array('id' => array('in', array_keys($bindBonus))))
							->save(array('bonus' => array('exp', "CASE id {$setBonusFields} END"),
										'orderCount' => array('exp', 'orderCount+1')));
		}
	}
	
	/**
	 * 更新用户产品推广用户的业绩
	 */
	public function updateUserProductPromotion( $order ) {
		$orderId = $order['id'];
		$cid = $order['cid'];
		$goodsList = M("DistributionShopOrderGoods")->where("order_id=%d", $orderId)->select();
		$productUserGoods = array(
				/*'用户id' => array(
					 '产品id' => array(
					 		'saledTotal(销售总和)' => 0.00,
					 		'rewardsTotal(佣金)' => 0.00,
					 		'dealerRewardsTotal(特约佣金)' => 0.00,
					 ),
				),*/
		);
		foreach ( $goodsList as $goods) {
			/* 单项总分成用户 */
			$totalUser = array();
			/*分配佣金*/
			if ( $goods['reward_uids'] ) {
				$userBonus = array_combine(explode(',', $goods['reward_uids']), explode(',', $goods['reward_bonus']));
			}
			/*各用户下*/
			foreach ( $userBonus as $uid => $bonus ) {
				$productUserGoods[$uid][$goods['product_id']]['rewardsTotal'] += $userBonus[$uid]*1; // 基础佣金总额
				$totalUser[$uid] = 1;
			}
			/*特销商佣金*/
			if ( $goods['reward_uids_dealer'] ) {
				$userBonusDealer = array_combine(explode(',', $goods['reward_uids_dealer']), explode(',', $goods['reward_bonus_dealer']));
			}
			/*各用户下*/
			foreach ( $userBonusDealer as $uid => $bonus ) {
				$productUserGoods[$uid][$goods['product_id']]['dealerRewardsTotal'] += $userBonusDealer[$uid]*1; // 特销商佣金总额
				if ( !isset($totalUser[$uid]) ) {
					$totalUser[$uid] = 1;
				}
			}
			foreach ( $totalUser as $uid => $v ) {
				/*各商品佣金*/
				$productUserGoods[$uid][$goods['product_id']]['orderCount'] = 1;
				$productUserGoods[$uid][$goods['product_id']]['saledTotal'] += $goods['product_number']*$goods['product_price']; // 消售总额
			}
		}
		foreach ( $productUserGoods as $uid => $pros ) {
			foreach ( $pros as $productId => $pro ) {
				$m = M("DistributionShopGoodsPromotion");
				$dsgp = $m->where('uid=%d and productId=%d', $uid, $productId)->find();
				if ( $dsgp ) {
					$m->where('uid=%d and productId=%d', $uid, $productId)->data(array(
							'orderCount' => array('exp', "orderCount+{$pro['orderCount']}"),
							'saledTotal' => array('exp', "saledTotal+{$pro['saledTotal']}"),
							'rewardsTotal' => array('exp', "rewardsTotal+".($pro['rewardsTotal'])*1),
							'dealerRewardsTotal' => array('exp', "dealerRewardsTotal+".($pro['dealerRewardsTotal'])*1),
					))->save();
				} else {
					$m->add(array(
							'cid' => $cid,
							'uid' => $uid,
							'productId' => $productId,
							'orderCount' => $pro['orderCount'],
							'saledTotal' => $pro['saledTotal'],
							'rewardsTotal' => $pro['rewardsTotal']*1,
							'dealerRewardsTotal' => $pro['dealerRewardsTotal']*1,
					));
				}
			}
		}
	}
	
	/**
	 * 计算订单捐赠总额
	 * @param unknown $order
	 * @param number $projectId
	 */
	public function getDonateTotal( $order ) {
	    $orderId = $order['id'];
	    $cid = $order['cid'];
	    $uid= $order['uid'];
	    $goodsList = M("DistributionShopOrderGoods")->where("order_id=%d", $orderId)->select();
	    $total = 0;
	    foreach ( $goodsList as $goods) {
	        $goodsSnap = unserialize($goods['goods_snap']);
	        $goodsId = $goods['product_id'];
	        $goodsNumber = $goods['product_number'];
	        $donateMoney = max(floatval($goodsSnap['donate_money']*1), 0);
	        $total+=$donateMoney;
	    }
	    return $total;
	}
	
	/**
	 * 捐赠
	 * @param $order 订单
	 * array(
	 *    'id' => 2,
	 *    'cid' => 0,
	 *    'uid' => 56,
	 * )
	 * @param 类型
	 */
	public function donate( $order, $projectId = 0 ) {
	    $orderId = $order['id'];
	    $cid = $order['cid'];
	    $uid= $order['uid'];
	    $goodsList = M("DistributionShopOrderGoods")->where("order_id=%d", $orderId)->select();
        foreach ( $goodsList as $goods) {
            $goodsSnap = unserialize($goods['goods_snap']);
            $goodsId = $goods['product_id'];
            $goodsNumber = $goods['product_number'];
            $donateMoney = max(floatval($goodsSnap['donate_money']*1), 0);
            $donateMoney and DistributionShopDonate::add($cid, $uid, $orderId, $goodsId, $goodsNumber, $donateMoney, $projectId);
        }
	}
}